package com.jy.appmarket.screenlock.view;

import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.utils.Encryptor;
import com.jy.appmarket.screenlock.utils.PatternLockerUtils;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


/**
 * 类说明：
 * 
 * @author jie.li
 * @date 2015-3-9
 * @version 1.0
 */
public class LockNumberView extends LinearLayout implements OnClickListener {
	/**
	 * 设置数字密码
	 */
	public static final int SETTING_PASSWORD = 0;
	/**
	 * 修改数字密码
	 */
	public static final int CHANGE_PASSWORD = 1;
	/**
	 * 数字解锁
	 */
	public static final int UNLOCK_PASSWORD = 2;

	public static final int OK = -1;
	public static final int CANCELED = 0;
	public static final int EMS_CALL = -2;

	private int mType;
	// 展示位数的4个点
	private LinearLayout showNumberLayout;
	// 显示的4个点的图片
	private ImageView[] imgs = new ImageView[4];
	// 数字键盘
	private TextView number_0, number_1, number_2, number_3, number_4,
			number_5, number_6, number_7, number_8, number_9;
	// 更改的密码
	private String password = "";
	private static final String PASSWORD_SALT = "7xn7@c$";
	private String oldPasscode = null;
	private TextView tvMessage, tvDelete, tvEmergency;
	private Vibrator mVibrator;
	private Context mContext;
	private OnLockNumberListener lockNumberListener;
	private int mFailed = 0;
	private Handler mHandler = new Handler();

	public void setOnLockNumberListener(OnLockNumberListener listener) {
		lockNumberListener = listener;
	}

	public LockNumberView(Context context, int type) {
		super(context);
		mContext = context;
		mType = type;
		initView();
	}

	public LockNumberView(Context context, AttributeSet attrs, int type) {
		super(context, attrs);
		mContext = context;
		mType = type;
		initView();
	}

	public LockNumberView(Context context, AttributeSet attrs, int defStyle,
			int type) {
		super(context, attrs, defStyle);
		mContext = context;
		mType = type;
		initView();
	}

	private void initView() {
		mVibrator = (Vibrator) mContext
				.getSystemService(Context.VIBRATOR_SERVICE);

		LayoutInflater.from(mContext).inflate(R.layout.view_lock_number_layout,
				this);
		showNumberLayout = findViewById(R.id.password_layout);

		tvMessage = findViewById(R.id.fragment_title);
		for (int i = 0; i < 4; i++) {
			imgs[i] = (ImageView) showNumberLayout.getChildAt(i);
			imgs[i].setEnabled(true);
			imgs[i].setTag(i);
		}
		setHideImageView();

		// 数字键盘
		number_0 = findViewById(R.id.digit_0_iv);
		number_1 = findViewById(R.id.digit_1_iv);
		number_2 = findViewById(R.id.digit_2_iv);
		number_3 = findViewById(R.id.digit_3_iv);
		number_4 = findViewById(R.id.digit_4_iv);
		number_5 = findViewById(R.id.digit_5_iv);
		number_6 = findViewById(R.id.digit_6_iv);
		number_7 = findViewById(R.id.digit_7_iv);
		number_8 = findViewById(R.id.digit_8_iv);
		number_9 = findViewById(R.id.digit_9_iv);

		number_0.setOnClickListener(this);
		number_1.setOnClickListener(this);
		number_2.setOnClickListener(this);
		number_3.setOnClickListener(this);
		number_4.setOnClickListener(this);
		number_5.setOnClickListener(this);
		number_6.setOnClickListener(this);
		number_7.setOnClickListener(this);
		number_8.setOnClickListener(this);
		number_9.setOnClickListener(this);

		// 紧急电话
		tvEmergency = findViewById(R.id.emergency_call_tv);
		// TODO:暂时屏蔽
		tvEmergency.setVisibility(View.INVISIBLE);
		tvEmergency.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (LockPrefs.getTouchSoundFeedback(mContext)) {
					mVibrator.vibrate(100);
				}
				lockNumberListener.OnLockNumber(EMS_CALL);
				// ComponentName comp = new ComponentName("com.android.phone",
				// "com.android.phone.EmergencyDialer");
				// Intent intent = new Intent();
				// intent.setComponent(comp);
				// mContext.startActivity(intent);
			}
		});

		// 删除
		tvDelete = findViewById(R.id.delete_tv);
		tvDelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (LockPrefs.getTouchSoundFeedback(mContext)) {
					mVibrator.vibrate(100);
				}
				deletePassword();
			}
		});

		switch (mType) {
		case SETTING_PASSWORD:
		case CHANGE_PASSWORD:
			tvDelete.setVisibility(View.GONE);
			tvEmergency.setVisibility(View.GONE);
			break;
		case UNLOCK_PASSWORD:
			tvDelete.setVisibility(View.VISIBLE);
			// tvEmergency.setVisibility(View.VISIBLE);
			// TODO:
			tvEmergency.setVisibility(View.INVISIBLE);
			break;
		default:
			break;
		}

	}

	/**
	 * 当前显示的有几位，然后剩下的隐藏
	 */
	public void setHideImageView() {
		int length = getPassword().length();
		for (int i = 0; i < length; i++) {
			imgs[i].setEnabled(false);
		}
		for (int i = 0; i < 4 - length; i++) {
			imgs[3 - i].setEnabled(true);
		}
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public void onClick(View v) {
		int num = -1;
		if (LockPrefs.getTouchSoundFeedback(mContext)) {
			mVibrator.vibrate(100);
		}
		switch (v.getId()) {
		case R.id.digit_0_iv:
			num = 0;
			break;
		case R.id.digit_1_iv:
			num = 1;
			break;
		case R.id.digit_2_iv:
			num = 2;
			break;
		case R.id.digit_3_iv:
			num = 3;
			break;
		case R.id.digit_4_iv:
			num = 4;
			break;
		case R.id.digit_5_iv:
			num = 5;
			break;
		case R.id.digit_6_iv:
			num = 6;
			break;
		case R.id.digit_7_iv:
			num = 7;
			break;
		case R.id.digit_8_iv:
			num = 8;
			break;
		case R.id.digit_9_iv:
			num = 9;
			break;

		default:
			break;
		}
		// 添加数字
		if (num != -1) {
			changePasswrod(num + "");
		}
	}

	/**
	 * 拼接传入进来的字符串输出密码
	 * 
	 * @param number
	 */
	private void changePasswrod(String passLock) {
		String passwordString = getPassword();
		if (TextUtils.isEmpty(passwordString) || passwordString.length() < 4) {
			setPassword(passwordString + passLock);
			setHideImageView();
			tvDelete.setText(R.string.delete);
			if (getPassword().length() == 4) {
				new Handler().post(new Runnable() {
					@Override
					public void run() {
						String newPassword = getPassword();
						switch (mType) {

						case SETTING_PASSWORD:
							if (oldPasscode == null) {
								tvMessage
										.setText(R.string.enter_password_again);
								oldPasscode = newPassword;
								// 重新输入密码
								setPassword("");
								setHideImageView();
							} else {
								if (newPassword.equals(oldPasscode)) {
									savePassword(newPassword);
									if (lockNumberListener != null) {
										lockNumberListener.OnLockNumber(OK);
									}

								} else {
									oldPasscode = null;
									tvMessage.setText(R.string.enter_password);
									passwordError();
								}
							}
							break;

						case CHANGE_PASSWORD:
							if (checkPasscode(newPassword)) {
								if (lockNumberListener != null) {
									lockNumberListener.OnLockNumber(OK);
								}
							} else {
								passwordError();
							}
							break;

						case UNLOCK_PASSWORD:
							if (checkPasscode(newPassword)) {
								if (lockNumberListener != null) {
									lockNumberListener.OnLockNumber(OK);
								}

							} else {
								passwordError();
							}
							break;

						default:
							break;
						}
					}
				});
			}

		} else {

		}
	}

	private void savePassword(String password) {

		if (password == null) {
			// editor.remove(PASSWORD_PREFERENCE_KEY);
			// editor.commit();
			// this.disable();
		} else {
			password = PASSWORD_SALT + password + PASSWORD_SALT;
			password = Encryptor.getSHA1(password);
			LockPrefs.setNumberLockPassword(mContext, password);
		}
	}

	public boolean checkPasscode(String passcode) {
		passcode = PASSWORD_SALT + passcode + PASSWORD_SALT;
		passcode = Encryptor.getSHA1(passcode);
		String storedPasscode = "";

		storedPasscode = LockPrefs.getNumberLockPassword(mContext);

        return passcode.equalsIgnoreCase(storedPasscode);
	}

	private void passwordError() {
		setPassword("");
		setHideImageView();
		if (getPassword().length() == 0) {
			tvDelete.setText(R.string.cancel);
		}
		if (LockPrefs.getTouchSoundFeedback(mContext)) {
			mVibrator.vibrate(500);
		}
		switch (mType) {
		case SETTING_PASSWORD:
			tvMessage.setText(R.string.enter_password_disagree);
			break;
		case CHANGE_PASSWORD:
			tvMessage.setText(R.string.enter_password_error);
			break;
		case UNLOCK_PASSWORD:
			mFailed++;
			int retry = 5 - mFailed;// 5次机会
			if (mFailed >= 5) {
				setNumberView(false);
				mHandler.postDelayed(attemptLockout, 2000);
			}
			if (retry >= 0) {
				if (retry == 0) {
					tvMessage.setText("您已5次输错密码，请3分钟后再试");
				} else {
					tvMessage.setText("密码错误，还可以再输入" + retry + "次");
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							tvMessage.setText("请输入密码");
						}
					}, 2000);
				}
			}

			break;

		default:
			break;
		}

	}

	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			new CountDownTimer(
					PatternLockerUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					String remainingText = "";
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					if (secondsRemaining >= 60) {
						remainingText = secondsRemaining / 60 + "分"
								+ secondsRemaining % 60 + "秒后重试";
					} else {
						remainingText = secondsRemaining + " 秒后重试";
					}
					if (secondsRemaining > 0) {
						tvMessage.setText(remainingText);
					} else {
						tvMessage.setText("请输入密码");
						tvMessage.setTextColor(Color.WHITE);
					}
				}

				@Override
				public void onFinish() {
					setNumberView(true);
					mFailed = 0;
				}
			}.start();
		}
	};

	private void setNumberView(boolean enable) {
		number_0.setEnabled(enable);
		number_1.setEnabled(enable);
		number_2.setEnabled(enable);
		number_3.setEnabled(enable);
		number_4.setEnabled(enable);
		number_5.setEnabled(enable);
		number_6.setEnabled(enable);
		number_7.setEnabled(enable);
		number_8.setEnabled(enable);
		number_9.setEnabled(enable);

	}

	/**
	 * 删除一个密码
	 */
	private void deletePassword() {
		String passwordString = getPassword();
		if (!TextUtils.isEmpty(passwordString) || passwordString.length() > 0) {
			setPassword(passwordString
					.substring(0, passwordString.length() - 1));
			setHideImageView();
			if (getPassword().length() == 0) {
				tvDelete.setText(R.string.cancel);
			}
		} else {
			// 密码已清空
			switch (mType) {

			case SETTING_PASSWORD:
			case CHANGE_PASSWORD:
				break;

			case UNLOCK_PASSWORD:
				// 锁屏界面点击取消
				if (lockNumberListener != null) {
					lockNumberListener.OnLockNumber(CANCELED);
				}
				break;

			default:
				break;
			}
		}
	}

	public interface OnLockNumberListener {
		void OnLockNumber(int result);
	}

}
